package com.blrs.service.indexInfo.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import com.blrs.common.utils.DateUtils;
import com.blrs.common.utils.ReflectionUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.file.FileUtils;
import com.blrs.domain.*;
import com.blrs.mapper.*;
import com.blrs.service.file.IFileCabinetInformationService;
import com.blrs.service.indexInfo.IInfoIndexService;
import com.blrs.system.domain.SysUploadFile;
import com.blrs.system.domain.SysUserRole;
import com.blrs.system.mapper.SysUploadFileMapper;
import com.blrs.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 首页信息服务Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-07
 */
@Service
public class InfoIndexServiceImpl implements IInfoIndexService
{
    @Autowired
    private InfoIndexMapper infoIndexMapper;
    @Autowired
    private IndexCollectionMapper indexCollectionMapper;
    @Autowired
    private IFileCabinetInformationService fileCabinetInformationService;
    @Autowired
    private DemandReleaseMapper demandReleaseMapper;
    @Autowired
    private SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    private ExternalDocumentMapper documentMapper;
    @Autowired
    private QuestionnaireInvestigationMapper questionnaireInvestigationMapper;
    @Autowired
    private ActivityTrainingMapper activityTrainingMapper;
    @Autowired
    private PolicyReleaseMapper policyReleaseMapper;
    @Autowired
    private InfoIndexCollectionMapper infoIndexCollectionMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private DemandReleaseMapper releaseMapper;
    @Autowired
    private DemandCollectionMapper demandCollectionMapper;



    /**
     * 查询首页信息服务
     * 
     * @param id 首页信息服务主键
     * @return 首页信息服务
     */
    @Override
    public InfoIndex selectInfoIndexById(String id)
    {
        return infoIndexMapper.selectInfoIndexById(id);
    }

    /**
     * 查询首页信息服务列表
     * 
     * @param infoIndex 首页信息服务
     * @return 首页信息服务
     */
    @Override
    public List<InfoIndex> selectInfoIndexList(InfoIndex infoIndex)
    {
        List<InfoIndex> list=null;
//        if (SecurityUtils.getUserId()!=1L){
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setUserId(SecurityUtils.getUserId());
//            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleList(sysUserRole);
//            infoIndex.setRoleId(sysUserRoles.get(0).getRoleId());
//          list = infoIndexMapper.selectInfoIndexList(infoIndex);
//        }else {
//           list= infoIndexMapper.selectInfoIndexListAdmin(infoIndex);
//        }
//        if (infoIndex.getOrgId()==100L && SecurityUtils.getUserId()==1L){
//            list= infoIndexMapper.selectInfoIndexListAdmin(infoIndex);
//        }else if (infoIndex.getOrgId()==100L && SecurityUtils.getUserId()!=1L){
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setUserId(SecurityUtils.getUserId());
//            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleList(sysUserRole);
//            infoIndex.setRoleId(sysUserRoles.get(0).getRoleId());
//            list = infoIndexMapper.selectInfoIndexList(infoIndex);
//        }else {
//            //我发布的，政策信息和需求信息需要展示到发送方
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setUserId(SecurityUtils.getUserId());
//            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleList(sysUserRole);
//            infoIndex.setRoleId(sysUserRoles.get(0).getRoleId());
//            list = infoIndexMapper.selectInfoIndexListBySelf(infoIndex);
//        }
        //2025-05-07  甲方要求修改所有信息展示一键发送的内容
        list=infoIndexMapper.selectInfoIndexListByOneClick(infoIndex);
        for (InfoIndex index : list) {
            String collection=infoIndexCollectionMapper.selectInfoIndexCollectionByOrgIdAndIndexId(index.getId(),SecurityUtils.getOrgId());
         if (StringUtils.isNotEmpty(collection)){
             index.setIsCollection(collection);
         }else {
             index.setIsCollection("no_col");
         }
        }
        return list;
    }

    /**
     * 新增首页信息服务
     * 
     * @param infoIndex 首页信息服务
     * @return 结果
     */
    @Override
    public int insertInfoIndex(InfoIndex infoIndex)
    {
        infoIndex.setCreateTime(DateUtils.getNowDate());
        return infoIndexMapper.insertInfoIndex(infoIndex);
    }

    /**
     * 修改首页信息服务
     * 
     * @param infoIndex 首页信息服务
     * @return 结果
     */
    @Override
    public int updateInfoIndex(InfoIndex infoIndex)
    {
        return infoIndexMapper.updateInfoIndex(infoIndex);
    }

    /**
     * 批量删除首页信息服务
     * 
     * @param ids 需要删除的首页信息服务主键
     * @return 结果
     */
    @Override
    public int deleteInfoIndexByIds(Long[] ids)
    {
        return infoIndexMapper.deleteInfoIndexByIds(ids);
    }

    /**
     * 删除首页信息服务信息
     * 
     * @param id 首页信息服务主键
     * @return 结果
     */
    @Override
    public int deleteInfoIndexById(String  id)
    {
        return infoIndexMapper.deleteInfoIndexById(id);
    }

    @Override
    public void createAndInsertInfoIndex(String infoId, String titleName, String orgName, Long orgId, String infoType,String route,Long menuId,String sendType) {
        InfoIndex infoIndex = new InfoIndex();
        infoIndex.setInfoId(infoId);
        infoIndex.setTitleName(titleName);
        infoIndex.setOrgName(orgName);
        infoIndex.setOrgId(orgId);
        infoIndex.setInfoType(infoType);
        infoIndex.setRoute(route);
        infoIndex.setIsCollection("no_col");
        infoIndex.setMenuId(menuId);
        infoIndex.setCreateTime(new Date());
        infoIndex.setSendType(sendType);
        infoIndexMapper.insertInfoIndex(infoIndex);
    }
    public static void copyFile(String sourceFilePath, String destinationFilePath) throws IOException {
        // 创建源文件和目标文件的路径对象
        Path sourcePath = Paths.get(sourceFilePath);
        Path destinationPath = Paths.get(destinationFilePath);

        // 执行文件复制
        Files.copy(sourcePath, destinationPath);
    }
    /**
     * 收藏信息
     * @param infoIndex
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int collectionInfo(InfoIndex infoIndex) throws IOException, NoSuchFieldException, IllegalAccessException {
        //1.添加到收藏夹表
        String collectionId=UUID.randomUUID().toString();
        IndexCollection indexCollection = new IndexCollection();
        indexCollection.setInfoIndexId(infoIndex.getId());
        indexCollection.setCreateTime(new Date());
        indexCollection.setOrgId(SecurityUtils.getOrgId());
        indexCollection.setOrgName(SecurityUtils.getOrgName());
        indexCollection.setType(infoIndex.getInfoType());
        indexCollection.setId(collectionId);
        indexCollection.setMenuId(infoIndex.getMenuId());
        indexCollectionMapper.insertIndexCollection(indexCollection);
        //如果是需求发布，需给当前需求发布的进行更改收藏状态
        if (infoIndex.getInfoType().equals("需求信息")){
            DemandCollection demandCollection = new DemandCollection();
            demandCollection.setDemandId(infoIndex.getInfoId());
            demandCollection.setOrgId(SecurityUtils.getOrgId());
            demandCollectionMapper.insertDemandCollection(demandCollection);
        }
        handleFileUpload(infoIndex, collectionId);
        InfoIndexCollection infoIndexCollection = new InfoIndexCollection();
        infoIndexCollection.setIndexId(infoIndex.getId());
        infoIndexCollection.setIsCollection("is_col");
        infoIndexCollection.setOrgId(SecurityUtils.getOrgId());
        infoIndexCollection.setId(collectionId);
        return infoIndexCollectionMapper.insertInfoIndexCollection(infoIndexCollection);
    }

    private void handleFileUpload(InfoIndex infoIndex, String extId) throws IOException, NoSuchFieldException, IllegalAccessException {
        SysUploadFile uploadFile = null;

        switch (infoIndex.getInfoType()) {
            case "需求信息":
                DemandRelease demandRelease = demandReleaseMapper.selectDemandReleaseByProjectId(infoIndex.getInfoId());
                uploadFile = sysUploadFileMapper.selectUrlByCodePay("demand", demandRelease.getUploadFile());
                break;
            case "问卷调查":
                QuestionnaireInvestigation questionnaireInvestigation = questionnaireInvestigationMapper.selectQuestionnaireInvestigationByQuestionnaireId(infoIndex.getInfoId());
                uploadFile = sysUploadFileMapper.selectUrlByCodePay("investigation", questionnaireInvestigation.getFileUpload());
                break;
            case "活动培训":
                ActivityTraining training = activityTrainingMapper.selectActivityTrainingByActivityId(infoIndex.getInfoId());
                uploadFile = sysUploadFileMapper.selectUrlByCodePay("train", training.getFileUpload());
                break;
            case "政策信息":
                PolicyRelease policyRelease = policyReleaseMapper.selectPolicyReleaseByPermissionId(infoIndex.getInfoId());
                uploadFile=sysUploadFileMapper.selectUrlByCodePay("policy",policyRelease.getUploadFile());
                break;
            case "新闻资讯":
                 uploadFile = sysUploadFileMapper.selectUrlByCodePay("releaseFile", infoIndex.getInfoId());
                 break;
            case "行业动态":
                 uploadFile = sysUploadFileMapper.selectUrlByCodePay("releaseFile", infoIndex.getInfoId());
                 break;
            default:
                throw new IllegalArgumentException("收藏失败: " + infoIndex.getInfoType());
        }

        if (Objects.nonNull(uploadFile)) {
            UploadIndex(uploadFile, infoIndex.getInfoType(), extId, infoIndex);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int collectionNoInfo(InfoIndex infoIndex) {
        InfoIndexCollection indexCollection = infoIndexCollectionMapper.selectInfoIndexCollectionByOrgIdAndIndexIdAll(infoIndex.getId(), SecurityUtils.getOrgId());
        // 删除收藏夹数据
        indexCollectionMapper.deleteIndexCollectionById(infoIndex.getId(),SecurityUtils.getOrgId());
        //如果是需求发布，需给当前需求发布的进行更改收藏状态
        if (infoIndex.getTitleName().equals("需求信息")){
            DemandCollection demandCollection = new DemandCollection();
            demandCollection.setDemandId(infoIndex.getInfoId());
            demandCollection.setOrgId(SecurityUtils.getOrgId());
            demandCollectionMapper.deleteDemandCollectionByDemandId(demandCollection);
        }
        handleFileDeletion(indexCollection);
        InfoIndexCollection infoIndexCollection = new InfoIndexCollection();
        infoIndexCollection.setOrgId(SecurityUtils.getOrgId());
        infoIndexCollection.setIndexId(infoIndex.getId());
        return infoIndexCollectionMapper.deleteInfoIndexCollectionByIndexIdAndOrgId(infoIndexCollection);
    }

    @Override
    public List<InfoIndex> selectInfoIndexListCollection() {
        List<List<InfoIndex>> lists = new ArrayList<>();
        List<InfoIndex> list=new ArrayList<>();
//        Map<String, List<InfoIndex>> categorizedInfoIndex = new HashMap<>();
//        categorizedInfoIndex.put("需求信息", new ArrayList<>());
//        categorizedInfoIndex.put("问卷调查", new ArrayList<>());
//        categorizedInfoIndex.put("活动培训", new ArrayList<>());
//        categorizedInfoIndex.put("政策信息",new ArrayList<>());
//        categorizedInfoIndex.put("新闻资讯",new ArrayList<>());
//        categorizedInfoIndex.put("行业动态",new ArrayList<>());

        //管理员账号
        if (SecurityUtils.getOrgId()==100L){
            list = infoIndexMapper.selectInfoIndexListByCollectionAdmin(SecurityUtils.getOrgId());
        }else {
            //我发布的，政策信息和需求信息需要展示到发送方
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(SecurityUtils.getUserId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleList(sysUserRole);
            InfoIndex infoIndex = new InfoIndex();
            infoIndex.setRoleId(sysUserRoles.get(0).getRoleId());
            infoIndex.setOrgId(SecurityUtils.getOrgId());
            list = infoIndexMapper.selectInfoIndexListByCollection(infoIndex);
        }
//        for (InfoIndex index : list) {
//            List<InfoIndex> categoryList = categorizedInfoIndex.get(index.getInfoType());
//            if (categoryList != null) {
//               if (index.getTitleName().length()>=8){
//                   index.setTitleName(StringUtils.substring(index.getTitleName(),0,7)+"...");
//               }
//                categoryList.add(index);
//            }
//        }
        for (InfoIndex index : list) {
            if (index.getTitleName() != null && index.getTitleName().length() > 8) {
                index.setTitleName(index.getTitleName().substring(0, 7) + "...");
            }
        }
        return list;
    }

    private void handleFileDeletion(InfoIndexCollection indexCollection) {
        SysUploadFile uploadFile = sysUploadFileMapper.selectUrlByCodePay("external", indexCollection.getId());
        if (Objects.nonNull(uploadFile)) {
            deleteUpload(uploadFile);
        }
    }



    public void deleteUpload(SysUploadFile uploadFile){
        //1.删除附件
        FileUtils.deleteFile(uploadFile.getPhyPath()+"/"+uploadFile.getNewFileName());
        //2.删除对应的外部文件数据
        documentMapper.deleteExternalDocumentByInternalId(uploadFile.getBusinessId());
        //3.删除对应的附件数据库信息
        sysUploadFileMapper.deleteSysUploadFileById(uploadFile.getId());
    }


    /**
     * 重新添加对应收藏文件数据信息
     * @param uploadFile
     * @param title
     * @param id
     * @throws IOException
     */
    public void UploadIndex(SysUploadFile uploadFile,String title,String id,InfoIndex infoIndex) throws IOException, NoSuchFieldException, IllegalAccessException {
        //2.在外部文件柜中创建文件夹，有的话就不创建，没有就创建
        //先获取当前企业的外部文件夹id
        String folderId = fileCabinetInformationService.selectExternalFolder(SecurityUtils.getOrgId());
        if (folderId != null){
            FileCabinetInformation fileCabinetInformation = new FileCabinetInformation();
            fileCabinetInformation.setCabinetName(infoIndex.getInfoType());
            fileCabinetInformation.setSuperiorCabinetId(folderId);
            fileCabinetInformationService.insertFileCabinetInformation(fileCabinetInformation);
            //(1).先复制对应文件
            String s = modifyFileName(uploadFile.getNewFileName(), title+new Date().getTime());
            String collectionPath=uploadFile.getPhyPath()+"/"+s;
            copyFile(uploadFile.getPhyPath()+"/"+uploadFile.getNewFileName(), collectionPath);
            //(2)文件数据添加到数据库
            uploadFile.setId(UUID.randomUUID().toString());
            uploadFile.setBusinessCode("external");
            uploadFile.setBusinessId(id);
            uploadFile.setNewFileName(s);
            uploadFile.setUrl(replaceFileNameInUrl(uploadFile.getUrl(),s));
            sysUploadFileMapper.insertSysUploadFile(uploadFile);
            //4.添加外部文件到文件柜(先去查外部文件夹)
            String fileId=fileCabinetInformationService.selectFileCabinetInformationByCabinetNameByExternal(title,SecurityUtils.getOrgId());
            ExternalDocument externalDocument = new ExternalDocument();
            externalDocument.setExternalId(id);
            externalDocument.setFileName(infoIndex.getTitleName());
            externalDocument.setCabinetId(fileId);
            externalDocument.setEstablishmentTime(new Date());
            externalDocument.setEstablishedName(SecurityUtils.getUsername());
            ReflectionUtils.setCommonPrivateProperty(externalDocument);
            documentMapper.insertExternalDocument(externalDocument);
        }
    }


    public static String modifyFileName(String filePath, String insertString) {
        // 创建File对象
        File file = new File(filePath);

        // 获取文件名和扩展名
        String fileName = file.getName();
        int lastDotIndex = fileName.lastIndexOf('.');
        String baseName = (lastDotIndex > 0) ? fileName.substring(0, lastDotIndex) : fileName;
        String extension = (lastDotIndex > 0) ? fileName.substring(lastDotIndex) : "";

        // 构造新文件名
        String newFileName = baseName + "_" + insertString + extension;


        return newFileName;
    }

    public static String replaceFileNameInUrl(String originalUrl, String newFileName) {
        // 查找最后一个斜杠的位置
        int lastSlashIndex = originalUrl.lastIndexOf('/');

        // 构造新的URL
        if (lastSlashIndex >= 0) {
            return originalUrl.substring(0, lastSlashIndex + 1) + newFileName;
        } else {
            // 如果URL不包含斜杠，直接返回新的文件名
            return newFileName;
        }
    }
}


